<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/30 0030
 * Time: 上午 10:15
 */
namespace app\api\controller;

use app\admin\model\Department;
use app\admin\model\SupervisionUsers;
use app\common\BaseHelper;

use PhpOffice\PhpSpreadsheet\IOFactory;
use think\Db;

use app\admin\model\Image;
use app\admin\model\SupervisionSchedule;
use app\admin\model\Letter as LetterMdl;
use think\Exception;
use think\Request;

/*
 * 信访件
 * */
class Letter extends BaseController
{
    /*
     * 服务首页意见反馈列表
     * */
    public function getList()
    {
        $param = self::getHttpParam();
        $start = 0;
        $length = 5;
        if (!empty($param->start)){
            $start = $param->start;
        }
        if (!empty($param->length)){
            $length = $param->length;
        }
        $model = db('letter');
        $where = [
            'status' => 4,
        ];
        $result = $model->where($where)->limit($start,$length)->order('createDate desc')->select();
        foreach ($result as &$v){
            $departmentName = $this->getDepartmentName($v);
            $v['deptNames'] = $departmentName;
        }
        if (empty($result)) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '未查到数据');
        }
        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $result);
    }

    /*
     * 详情
     * */
    public function getDetail(Request $request)
    {
        $param = $request->param();
        if (empty($param['id']) || empty($param['userId'])){
            return show(config('status.ERROR_STATUS'),'缺少参数','缺少参数');
        }

        $where = [
            'a.id' => $param['id']
        ];

        $model = db('letter');
        $fields = 'a.id as letterId , a.user_id as userId,a.status,a.reply,a.createDate as letter_time , title, content,v.p_name ,v.p_phone,v.sex,v.province,v.city,v.county,v.address';
        $result = $model->alias('a')
            ->where($where)
            ->field($fields)
            ->join('user v','a.user_id = v.id')
            ->find();

        $result['location'] = $result['province'].'-'.$result['city'].'-'.$result['county'].'-'.$result['address'];
        if($result['userId'] == $param['userId']){
            $result['showPingJia'] = true;
        }else{
            $result['showPingJia'] = false;
        }
        $result['imageAction'] = Image::where(['relatedId'=>$result['letterId']])->field('id as imgId,imgUrl')->select();
        $Supervision = \app\admin\model\Supervision::where('letterId',$result['letterId'])->field('id,letterId')->find();
        $result['supervisionScheduleVOS'] = [];
        if($Supervision){
            $fields = 'a.content,a.huibao_time, d.name,u.p_name';
            $model = db('SupervisionSchedule');
            $result['supervisionScheduleVOS'] = $model->alias('a')
                ->where(['a.supervisionId'=>$Supervision->id])
                ->field($fields)
                ->join('user u' ,'a.user_id = u.id')
                ->join('department d','u.departmentId = d.id')
                ->order('huibao_time')
                ->select();
        }

        if (empty($result)) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '未查到数据');
        }
        return show(config('status.SUCCESS_STATUS'),self::MSG_SUCCESS,$result);
    }

    /*
     * 评价信访件
     * */
    public function evaluateLetter()
    {
        $param = self::getHttpParam();
        if (empty($param->userId)){
            return show(config('status.ERROR_STATUS'),self::NOT_PARAM,'userId 不能为空');
        }
        if (empty($param->letterId)){
            return show(config('status.ERROR_STATUS'),self::NOT_PARAM,'letterId 不能为空');
        }
        if (empty($param->status)){
            return show(config('status.ERROR_STATUS'),self::NOT_PARAM,'status 不能为空');
        }
        if ($param->status != 4){
            return show(config('status.ERROR_STATUS'),self::NOT_PARAM,'信访件状态不正确');
        }
        $model = db('letter');
        $where = [
            'id'      => $param->letterId,
            'user_id' => $param->userId,
            'status'  => $param->status
        ];
        $result = $model->update(['reply'=>$param->reply],$where,true);
        if (!$result){
            return show(config('status.ERROR_STATUS'),self::NOT_DATA,'未查到数据');
        }
        return show(config('status.SUCCESS_STAUTS'),self::MSG_SUCCESS,'评价成功');
    }

    /**
     * 写信
     * @return \think\Response
     */
    public function saveLetter()
    {
        $param = self::getHttpParam();
        if (empty($param->userId)){
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId 不能为空');
        }
        if (empty($param->title)){
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '标题不能为空');
        }
        if (empty($param->content)){
            return show(config('status.ERROR_STATUS'),self::NOT_PARAM,'内容不能为空');
        }
        Db::startTrans();
        try{
            $User = \app\admin\model\User::get($param->userId);
            if($User->type == 2){
                $model = db('letter');
                if (!isset($param->id)){
                    //新增
                    $data = [
                        'id'     => BaseHelper::getUUID(),
                        'title'  => $param->title,
                        'content'=> $param->content,
                        'user_id'=> $param->userId,
                        'createDate' => date('Y-m-d H:i:s',time())
                    ];
                    $result = $model->insert($data);
                    //用户信访次数加一
                    $User->setInc('number',1);
                    if (!empty($result)){
                        if(isset($param->files) && !empty($param->files)){
                            $list = [];
                            foreach($param->files as $v)
                            {
                                $id = BaseHelper::getUUID();
                                array_push($list,['id'=>$id,'imgUrl'=>$v,'relatedId'=>$data['id'],'created' => time()]);
                            }
                            $imagemodel = new Image();
                            $imagemodel->saveAll($list,false);
                        }

                    }else{
                        return show(config('status.ERROR_STATUS'), '提交信件失败', '提交信件失败');
                    }

                }elseif(isset($param->id) && !empty($param->id)){
                    //修改
                    $data = [
                        'title'  => $param->title,
                        'content'=> $param->content,
                        'user_id'=> $param->userId,
                        'updateDate' => date('Y-m-d H:i:s',time())
                    ];
                    $result = $model->where(['id'=>$param->id])->update($data,true);
                    if (!empty($result)){
                        //先删除附件
                        $imgcount = Image::where('relatedId',$param->id)->count();
                        if($imgcount>0){
                            Image::where('relatedId',$param->id)->delete();
                        }
                        if($param->files){
                            $list = [];
                            foreach ($param->files as $v){
                                $id = BaseHelper::getUUID();
                                array_push($list,['id'=>$id,'imgUrl'=>$v,'relatedId'=>$param->id,'created' => time()]);
                            }
                            $imagemodel = new Image();
                            $imagemodel->saveAll($list,false);
                        }
                    }else{
                        return show(config('status.ERROR_STATUS'), '提交信件失败', '提交信件失败');
                    }
                }
            }else{
                return show(config('status.ERROR_STATUS'), '该用户不是信访用户', '该用户不是信访用户');
            }

            Db::commit();
            return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, '保存成功');
        }catch (Exception $ex){
            Db::rollback();
            return show(config('status.ERROR_STATUS'), $ex->getMessage(), '提交信件失败1');
        }

    }

    /*
     * 编辑
     * */
    public function editFeedback()
    {
        $param = self::getHttpParam();
        if (empty($param->userId)){
            return show(config('status.ERROR_STATUS'),self::NOT_PARAM,'userId不能为空');
        }
        if (empty($param->letterId)){
            return show(config('status.ERROR_STATUS'),self::NOT_PARAM,'letterId不能为空');
        }
        $where = [
            'id' => $param->letterId,
            'user_id' => $param->userId
        ];
        $model = db('letter');
        $result = $model->where($where)->find();
        $model = db('Image');
        $Image =$model->where('relatedId',$result['id'])->select();
        $result['files'] = $Image;
        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $result);
    }

    //获取我的信访数量
    public function userLetterCount(Request $request){
        $param = $request->param();
        if(empty($param['id'])){
            return show(config('status.ERROR_STATUS'),'参数不合法','参数不合法');
        }
        $count = \app\admin\model\Letter::where('user_id',$param['id'])->where('status','in',[1,3,4])->count();
        return show(config('status.SUCCESS_STATUS'), 'ok', $count);
    }

    //我的信访列表
    public function getMyList(Request $request){
        $param = $request->param();
        if(empty($param['id'])){
            return show(config('status.ERROR_STATUS'),'参数不合法','参数不合法');
        }
        $Letter = \app\admin\model\Letter::where('user_id',$param['id'])->where('status','in',[1,3,4])->order('createDate DESC')->select();

        if($Letter){
            foreach ($Letter as &$v){
                $departmentName = $this->getDepartmentName($v);
                $v['deptNames'] = $departmentName;
            }
            return show(config('status.SUCCESS_STATUS'), 'ok', $Letter);
        }else{
            return show(config('status.ERROR_STATUS'),'暂无数据',null);
        }
    }

    //查看信访评价
    public function lookevaluate(Request $request){
        $param = $request->param();
        if(empty($param['id'])){
            return show(config('status.ERROR_STATUS'),'参数不合法','参数不合法');
        }
        $Letter = \app\admin\model\Letter::get($param['id']);
        if($Letter){
            if($Letter->reply){
                return show(config('status.SUCCESS_STATUS'), 'ok', $Letter);
            }else{
                return show(config('status.ERROR_STATUS'),'暂无数据',null);
            }
        }else{
            return show(config('status.ERROR_STATUS'),'暂无数据',null);
        }
    }
    //我的-信访中心
    public function letterList(Request $request){
        $param = $request->param();
        if($param['type'] != 1 && $param['type'] != 2 && $param['type'] != 3){
            return show(config('status.ERROR_STATUS'),'参数不合法','参数不合法');
        }
        if($param['type'] == 1){
            $where = [
                'status' => 1
            ];
        }elseif ($param['type'] == 2){
            $where = [
                'status' => 3
            ];
        }else{
            $where = [
                'status' => 4
            ];
        }
        $Letter = \app\admin\model\Letter::where($where)->select();
        if($Letter){
            foreach ($Letter as &$v){
                $deptNames = '';
                if($v['status']==3 || $v['status']==4){
                    $Supervision = \app\admin\model\Supervision::where('letterId',$v['id'])->field('id')->find();
                    $SupervisionUsers = SupervisionUsers::where('supervisionId',$Supervision['id'])->field('dept_id')->select();
                    $list = [];
                    foreach ($SupervisionUsers as $value){
                        array_push($list,$value['dept_id']);

                    }
                    array_unique($list);
                    $Department = Department::all($list);
                    $res = [];
                    foreach ($Department as $val){
                        array_push($res,$val['name']);
                    }
                    $names = implode('、',$res);
                    $deptNames .= $names;
                }
                $v['deptNames'] = $deptNames;
            }
            return show(config('status.SUCCESS_STATUS'), 'ok', $Letter);
        }else{
            return show(config('status.ERROR_STATUS'),'暂无数据',null);
        }
    }

    /*
     * 删除信访件
     * */
    public function delLetter()
    {
        $param = self::getHttpParam();
        if (empty($param->id)){
            return show(config('status.ERROR_STATUS'),self::NOT_PARAM,'id不能为空');
        }
        if (empty($param->userId)){
            return show(config('status.ERROR_STATUS'),self::NOT_PARAM,'userId不能为空');
        }
        $where = [
            'id' => $param->id,
            'user_id' => $param->userId,
        ];
        $model = db('letter');
        $result = $model->where($where)->update(['status'=>2],true);

        if (!$result){
            return show(config('status.ERROR_STATUS'),self::NOT_DATA,'创建者才能删除');
        }
        return show(config('status.SUCCESS_STATUS'),self::MSG_SUCCESS,'删除成功');
    }

    private function getDepartmentName($value){

        $deptNames = '';
        if($value['status']==3 || $value['status']==4){
            $Supervision = \app\admin\model\Supervision::where('letterId',$value['id'])->field('id')->find();
            $SupervisionUsers = SupervisionUsers::where('supervisionId',$Supervision['id'])->field('dept_id')->select();
            $list = [];
            foreach ($SupervisionUsers as $v){
                array_push($list,$v['dept_id']);

            }
            array_unique($list);
            $Department = Department::all($list);
            $res = [];
            foreach ($Department as $val){
                array_push($res,$val['name']);
            }
            $names = implode('、',$res);
            $deptNames .= $names;
        }
        return $deptNames;

    }
}
